const { ipcMain, BrowserWindow } = require("electron");
//抓取百度屏幕
//1.创建一个新的屏幕，将其设置为不显示，并且为离线的screen
//2.将url嵌入到新的屏幕中；
//3.页面加载完成后捕获页面区域（返回一个Promise<NativeImage>）
//4.使用NativeImage提供的方法 toDataURL() 得到base64的图片地址
//5.将base64位的地址赋值给渲染页面的src，即可页面显示
const getSource = (url) => {
    return new Promise((resolve, reject) => {
        const win = new BrowserWindow({
            width: 500,
            height: 500,
            show: false,
            webPreferences: {
                offscreen: true, //离线的screen，窗口只在内存中，不在页面中构建
            },
        });
        win.loadURL(url);
        win.webContents.on("did-finish-load", async () => {
            const title = win.getTitle();
            try {
                // nativeImage
                const image = await win.webContents.capturePage();
                const screenshot = image.toDataURL()
                resolve({
                    title,
                    screenshot,
                    url,
                });
            } catch (error) {
                reject(error);
            }
        });
    });
};

ipcMain.handle("on-url-event", async (event, url) => {
    const result = await getSource(url)
    return result;
});
